package com.weilf.zuul.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jmnarloch.spring.cloud.ribbon.support.RibbonFilterContextHolder;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义实现的filter
 * @author weil-f
 * @date 2021/3/1022:53
 */
@Component
public class MyZuulFilter extends ZuulFilter {
    /**
     * 过滤器的四种类型至一
     * pre 在请求之前执行
     * route 在路由中执行
     * post 在请求后执行
     * error 在发生错误的时候执行
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.ROUTE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 正式环境中应该先获取token，在解析token 获取用信息，查看是否已经具备了内测的资格；
        // 为了方便演示这里就写死了

        String hasPermission = request.getHeader("permission");
        if("YES".equals(hasPermission)){
            RibbonFilterContextHolder.getCurrentContext().add("hasPermission","YES");
        }else if("NO".equals(hasPermission)){
            RibbonFilterContextHolder.getCurrentContext().add("hasPermission","NO");
        }
        return null;
    }
}
